/*
 * Copyright (C) 2008-12  Bernhard Hobiger
 *
 * This file is part of HoDoKu.
 *
 * HoDoKu is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * HoDoKu is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with HoDoKu. If not, see <http://www.gnu.org/licenses/>.
 */

package sudoku;

import generator.BackgroundGenerator;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Creates a new sudoku while displaying a progress dialog. The creation is really
 * delegated to {@link #generator}.
 * 
 * @author  hobiwan
 */
public class GenerateSudokuProgressDialog extends javax.swing.JDialog implements Runnable {
    private static final long serialVersionUID = 1L;
    /** The newly generated sudoku. */
    private Sudoku2 sudoku;
    /** The background thread, that is used to run the {@link #generator}. */
    private Thread thread;
    /** The {@link DifficultyLevel} of the new sudoku. */
    private DifficultyLevel level;
    /** The {@link GameMode}for the new sudoku. */
    private GameMode mode;
    /** The real generator. */
    private BackgroundGenerator generator;
    
   /**
     * Creates a new instance.
     * @param parent
     * @param modal
     * @param level
     * @param mode  
     */
    public GenerateSudokuProgressDialog(java.awt.Frame parent, boolean modal, DifficultyLevel level,
            GameMode mode) {
        super(parent, modal);
        initComponents();
        getRootPane().setDefaultButton(cancelButton);
        KeyStroke escapeKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false);
        Action escapeAction = new AbstractAction() {
            private static final long serialVersionUID = 1L;
            @Override
            public void actionPerformed(ActionEvent e) {
                setVisible( false );
            }
        };
        getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(escapeKeyStroke, "ESCAPE");
        getRootPane().getActionMap().put("ESCAPE", escapeAction);
        
        this.level = level;
        this.mode = mode;
        thread = new Thread(this);
        // start the thread only when window is shown (formWindowOpened)
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        progressLabel = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        cancelButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("intl/GenerateSudokuProgressDialog"); // NOI18N
        setTitle(bundle.getString("GenerateSudokuProgressDialog.title")); // NOI18N
        setLocationByPlatform(true);
        setModal(true);
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        progressLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        progressLabel.setText("0"); // NOI18N

        cancelButton.setMnemonic(java.util.ResourceBundle.getBundle("intl/GenerateSudokuProgressDialog").getString("GenerateSudokuProgressDialog.cancelButton.mnemonic").charAt(0));
        cancelButton.setText(bundle.getString("GenerateSudokuProgressDialog.cancelButton.text")); // NOI18N
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });
        jPanel1.add(cancelButton);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 196, Short.MAX_VALUE)
                    .addComponent(progressLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 196, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addComponent(progressLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cancelButtonActionPerformed(ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        thread.interrupt();
        try {
            thread.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Interrupted while waiting for generation thread", ex);
        }
        sudoku = null;
        setVisible(false);
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        cancelButtonActionPerformed(null);
    }//GEN-LAST:event_formWindowClosing

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        // progress window is open -> start the Thread (important, because
        // some JRE implementations are so slow that the creation is complete before the
        // window has been drawn; the setVisible(false) will then be useless
        // and the window will not be closed
        thread.start();
//        System.out.println("formWindowOpened!");
    }//GEN-LAST:event_formWindowOpened

    /**
     * The thread: creates a puzzle and closes the dialog.
     */
    @Override
    public void run() {
        generator = new BackgroundGenerator();
        sudoku = generator.generate(level, mode, this);
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                setVisible(false);
            }
        });
    }

    /**
     * Updates the {@link #progressLabel}.
     */
    public void updateProgressLabel() {
        progressLabel.setText(Integer.toString(generator.getAnz()));
    }

    /**
     * Delivers the newsudoku back to the caller.
     *
     * @return
     */
    public Sudoku2 getSudoku() {
        return sudoku;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new GenerateSudokuProgressDialog(new javax.swing.JFrame(), true,
                        Options.getInstance().getDifficultyLevels()[DifficultyType.EASY.ordinal()],
                        GameMode.PLAYING).setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel progressLabel;
    // End of variables declaration//GEN-END:variables
    
}
